package com.zyf.chapter02.structure.proxy;

import com.zyf.chapter01.practice.v3.MetricsCollector;
import com.zyf.chapter01.principle.practice.RequestInfo;

/**
 * 静态代理
 * 使用委托的方式，调用原始类来执行业务代码。以此来实现解耦
 * 该方式使用前提：原始类提供了接口，如 {@link IUserController}
 * @author yifeng
 * @see IUserController
 */
public class V1UserControllerProxy implements IUserController {
    private MetricsCollector metricsCollector;
    private UserController userController;

    public V1UserControllerProxy(UserController userController) {
        this.userController = userController;
        metricsCollector = new MetricsCollector();
    }

    @Override
    public UserVo login(String telephone, String password) {
        long startTimestamp = System.currentTimeMillis();

        // 委托
        UserVo userVo = userController.login(telephone, password);

        long endTimeStamp = System.currentTimeMillis();
        long responseTime = endTimeStamp - startTimestamp;
        RequestInfo requestInfo = new RequestInfo("login", responseTime, startTimestamp);
        metricsCollector.recordRequest(requestInfo);
        return null;
    }

    @Override
    public UserVo register(String telephone, String password) {
        long startTimestamp = System.currentTimeMillis();

        // 委托
        UserVo userVo = userController.register(telephone, password);

        long endTimeStamp = System.currentTimeMillis();
        long responseTime = endTimeStamp - startTimestamp;
        RequestInfo requestInfo = new RequestInfo("register", responseTime, startTimestamp);
        metricsCollector.recordRequest(requestInfo);
        return null;
    }

    public static void main(String[] args) {
        // UserControllerProxy 使用举例
        // 因为原始类和代理类实现相同的接口，是基于接口而非实现编程
        // 将 UserController 类对象替换为 UserControllerProxy 类对象，不需要改动太多代码
        IUserController userController = new V1UserControllerProxy(new UserController());
    }
}
